local paynspraytable = {} -- a table of all of the paynspray locations on the map to make collision checks easy
-- TODO: add revenues for the owner once the business script is in
local paynspray1 = createBlip(1025, -1023, 31, 63, 2, 255, 0, 0, 255, 0, 400)
local paynspray2 = createBlip(-2426, 1018, 49, 63, 2, 255, 0, 0, 255, 0, 400)
local paynspray3 = createBlip(-1904, 208, 40, 63, 2, 255, 0, 0, 255, 0, 400)
local paynspray4 = createBlip(720, -454, 15, 63, 2, 255, 0, 0, 255, 0, 400)

table.insert(paynspraytable, createMarker(1025,-1023,31,'cylinder'))
table.insert(paynspraytable, createMarker(-2426,1018,49,'cylinder'))
table.insert(paynspraytable, createMarker(-1904,208,40,'cylinder'))
table.insert(paynspraytable, createMarker(720,-454,15,'cylinder'))

function RepairCar(vehicle)
	local cost = 0
	local wheelStates = {getVehicleWheelStates(vehicle)}
	local driver = getVehicleOccupant(vehicle, 0)
	local occupants = {getVehicleOccupants(vehicle)}
	
	for i=0,7 do
		local doorState = getVehicleDoorState(vehicle, i) -- TODO: save the damage model when the player parks their car
		if doorState == 2 or doorState == 3 or doorState == 4 then
			cost = cost + 400
		end
	end
	
	for i=0, tableLength(wheelStates) do
		if wheelStates[i] == 1 or wheelStates[i] == 2 then
			cost = cost + 200
		end
	end
	
	for i=0, 7 do
		local panelState = getVehiclePanelState(vehicle, i)
		if panelState == 1 or panelState == 2 then
			cost = cost + 150
		elseif panelState == 3 then
			cost = cost + 250
		end
	end
	
	cost = cost + (1000 - getElementHealth(vehicle))
	cost = math.floor(cost)
	
	if getPlayerMoney(driver) >= cost then
		for i=0, tableLength(occupants) do
			fadeCamera(occupants[i], false)
		end
		
		takePlayerMoney(driver, cost)
		fixVehicle(vehicle)
		
		for i=0, tableLength(occupants) do
			setTimer(fadeCamera, 1500, 1, occupants[i], true)
			outputChatBox("Your vehicle has been resprayed! Cost: "..cost, occupants[i])
		end
	else
		for i=0, tableLength(occupants) do
			outputChatBox("You don't have enough money to respray your vehicle. Cost: "..cost, occupants[i])
		end
	end
end

function CheckMarker(hitElement)
	if getElementType(hitElement) == "player" then
		--setTimer(_, 1500, 1, _) -- hacky, fix this
		if isElementWithinMarker(hitElement,source) then
			if getElementHealth(getPedOccupiedVehicle(hitElement)) < 1000 then
				RepairCar(getPedOccupiedVehicle(hitElement))
			end
		end
	end
end

function tableLength(T) -- messy, make this a global function
	local count = 0
	for _ in pairs(T) do count = count + 1 end
	return count
end

for i=1,tableLength(paynspraytable) do
	addEventHandler("onMarkerHit", paynspraytable[i], CheckMarker)
end

